$(function (){
    // 1. 抽取变量：这个js文件中出现多少次${"#....}，JS引擎就会去对应的页面做多少次元素查找。现在这样集中整合后，每种选择器只做一次，后面都是直接用变量
    var roleDatagrid, roleDatagridEditAndDel, roleDialog, roleForm,allPermissions,selfPermissions;
    roleDatagrid =  $('#role_dg');
    roleDatagridEditAndDel =$('#role_dg_edit,#role_dg_del');
    roleDialog = $('#role_dialog');
    roleForm = $('#role_form');
    allPermissions = $('#allPermissions');
    selfPermissions = $('#selfPermissions');


    /*员工信息表格的初始化*/
    roleDatagrid.datagrid({
        url: "/role_list",
        fit: true,
        fitColumns: true,
        rownumbers: true,
        pagination: true,
        singleSelect: true,
        toolbar:"#role_dg_tb",
        pageList:[2,3,10,20,30,40,50],
        columns: [
            [
                {field: "sn", title: "角色编号", width: 1, align: 'center'},
                {field: "name", title: "角色名称", width: 1, align: 'center'},
            ]
        ]
    });


    /*新增或更新编辑角色信息的对话框的初始化*/
    roleDialog.dialog({
        width: 700,
        height: 450,
        closed: true,
        buttons: '#role_dialog_bt'
    })


    allPermissions.datagrid({
        width:300,
        height:300,
        title:'所有权限',
        url:'permission_list',
        fitColumns: true,
        rownumbers: true,
        pagination:true,
        singleSelect:true,
        onDblClickRow:function (rowIndex, rowData){
            var rows = selfPermissions.datagrid("getRows");
            var flag = true;
            var index = -1;
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].id == rowData.id){
                    flag = false;
                    index = i;
                    break;
                }
            }
            //如果flag = false 代表已经存在该权限，高亮选中，否则新增
            if (flag){
                selfPermissions.datagrid('appendRow',rowData);
            }else {
                selfPermissions.datagrid('selectRow',index);
            }
        },
        columns: [
            [
                {field: "name", title: "权限名", width: 1, align: 'center'}
            ]
        ]
    });
    var PagerOfAllPermissions = allPermissions.datagrid('getPager');
    PagerOfAllPermissions.pagination({
        showPageList: false,
        showRefresh: false,
        displayMsg: ''
    });

    selfPermissions.datagrid({
        width:300,
        height:300,
        title:'已有权限',
        fitColumns: true,
        rownumbers: true,
        pagination:true,
        singleSelect:true,
        onDblClickRow:function (rowIndex, rowData){
            selfPermissions.datagrid('deleteRow',rowIndex);
        },
        columns: [
            [
                {field: "name", title: "权限名", width: 1, align: 'center'}
            ]
        ]
    });

    var PagerOfSelfPermissions = selfPermissions.datagrid('getPager');
    PagerOfSelfPermissions.pagination({
        showPageList: false,
        showRefresh: false,
        displayMsg: ''
    });



    //2. 统一管理方法,利用js对象
    var cmdFunc = {
        /*  新增按钮的逻辑 */
        add:function () {
            //TODO 可以同时调用多个方法吗
            roleDialog.dialog("open");
            roleDialog.dialog("setTitle", "新增");
            roleForm.form("clear");
            selfPermissions.datagrid('loadData',{total:0,rows:[]});
        },
        //保存新增员工时
        save:function (){
            //TODO 学习jquery的选择器
            var idVal = $('#role_form [name="id"]').val();
            var url;
            if (idVal){
                url = '/role_update'
            }else {
                url = '/role_save';
            }
            //表单提交异步请求
            roleForm.form('submit',{
                url: url,
                onSubmit:function(param){
                    var rows = selfPermissions.datagrid('getRows');
                    for (let i = 0; i < rows.length; i++) {
                        param["permissionList["+i+"].id"] = rows[i].id;
                    }
                },
                success:function (data) {
                    data = $.parseJSON(data);
                    if (data.success){
                        $.messager.alert("温馨提示",data.msg,"info",function (){
                            //新增成功后关闭对话框
                            roleDialog.dialog("close");
                            //刷新员工列表数据
                            roleDatagrid.datagrid('load');
                        });
                    }else {
                        $.messager.alert("温馨提示",data.msg,"warning");
                    }
            }
            });
        },

        edit:function () {
            var rowData = roleDatagrid.datagrid('getSelected');
            console.log(rowData)
            if (rowData){
                roleDialog.dialog("open");
                roleDialog.dialog("setTitle", "编辑");
                roleForm.form("load",rowData);//基于字段属性的同名 进行匹配显示的。
                var options = selfPermissions.datagrid('options');
                options.url = '/query_permissionByRid';
                selfPermissions.datagrid('load',{
                    rid : rowData.id
                });
            }else {
                $.messager.alert("温馨提示","请选中一条需要编辑的员工！","info");
            }
        },

        del:function () {
            var rowData = roleDatagrid.datagrid('getSelected');
            console.log(rowData)
            if (rowData){
                $.messager.confirm('确认','您确认想要删除该角色信息吗？',function(r){
                    if (r){
                        $.get(
                            '/role_delete?id='+rowData.id,
                            function (data) {
                                if (data.success){
                                    $.messager.alert("温馨提示",data.msg,"info");
                                    roleDatagrid.datagrid("reload");
                                }else {
                                    $.messager.alert("温馨提示",data.msg,"info");
                                }
                            },
                            "json"
                        );
                    }
                });
            }else {
                $.messager.alert("温馨提示","请选中一条需要删除的角色！","info");
            }

        },
        reload:function () {
            roleDatagrid.datagrid('reload');
        },

        cancel:function () {
            roleDialog.dialog("close");
        },

        searchBtn:function (){
            var keyVal = $("[name = 'keyword']").val();
            console.log(keyVal)
            roleDatagrid.datagrid('load',{
                keyword:keyVal
            });
        }
    };

    //3. 对按钮进行统一的监听
    $('a[data-cmd]').on('click',function (){
        var cmd = $(this).data('cmd');
        if (cmd){
            cmdFunc[cmd]();
        }
    });

});
















